//
//  mianPage.swift
//  ptbuy
//
//  Created by MyMac on 2024/11/7.
//

import SwiftUI
import AVFoundation
import AVKit
import CoreData

struct MainPage: View {

    
    @State private var about = false//关于
    @State private var feedback = false//意见反馈
    @State private var tranRecord = false//交易记录
    @State private var statisAnalysis = false//统计分析
    @State private var importExistData = false//导入已有数据
    
    //分享
    @State private var wxShowAlert = false
    
    @State private var isLoading: Bool = false//检查更新
    @State private var showingUpdateSheet: Bool = false//检查弹框
    @State private var networkStatus: Bool = false//检查弹框
    @State private var downurl:String = ""
    @State private var description:String = ""
    @State private var showUpdateAlert = false
    
    @State private var productName: String = ""//商品名称
    
    // 用来存储匹配的数据
    @State private var filteredData: [String] =  []
    //是否选择了名称的下啦提示
    @State private var isChose = false
    
    
    @State private var productPrice: String = ""//商品价格
    @State private var productTotalNum: Int16 = 0//总件数
    @State private var productTotalPrice: Int64 = 0//总价
   
    
    @FocusState private var isProductNameFocused: Bool//控制鼠标点击外部关闭软键盘
    @FocusState private var isProductPriceFocused: Bool//控制鼠标点击外部关闭软键盘
    @State private var isPhotoVideoAlertShowing = false
    @State private var isSaveAlertShowing = false
    @State private var showingModifyProductSheet = false // 控制点击商品修改弹出框显示
    
    @State private var showingSaveProductSheet = false // 控制点击交易确认弹出框显示
    @State private var isCleatAlert = false//清空列表
    @State private var isDeleteProductAlert = false//删除商品
    @State private var isTranConfAlert = false//交易确认按钮
    
    
    @State private var isPhotoOrView = false//是拍照/录像还是点击照片查看 false：拍照/录像；true:查看照片
    
    //转圈圈提示框
    @State private var isProgressLoading = false
    @State private var progress = 0.0
    @State private var showProgressAlert = false
    
    //下载进度框
    @State private var isWinShowingAlert = false
    @State private var showAlert = false           // 控制弹框的显示
    
    
    /*
     内容修改
     */
    @State private var productNameEdit: String = ""//商品名称
    @State private var productPriceEdit: String = ""//商品价格
    
    
    @Environment(\.managedObjectContext) private var viewContext
    
    @FetchRequest var product:FetchedResults<Product>
    @FetchRequest var client:FetchedResults<Client>
    
    @State private var productPojo:[ProductPojo] = []

    /*
     查询的所有作为输入名称框的提示信息
     */
    @FetchRequest var productAll:FetchedResults<Product>
    @State private var productArray:[String] = []

    
    init(){
        _product =  FetchRequest<Product>(
            sortDescriptors: [NSSortDescriptor(
                keyPath: \Product.myorder,
                ascending: false
            )],
            //%d：用于整数。
            predicate: NSPredicate(format: "status = %d", 0) // 初始时没有任何筛选条件
        )
        //初始化这个东西
        _productItem = State(initialValue: Product())
        
        
        _productAll =  FetchRequest<Product>(
            sortDescriptors: [NSSortDescriptor(
                keyPath: \Product.myorder,
                ascending: false
            )]
        )
        
        _client =  FetchRequest<Client>(
            sortDescriptors: [NSSortDescriptor(
                keyPath: \Client.myorder,
                ascending: false
            )]
        )
        
    }
    
    
    var isProductNameTextFieldEmpty: Bool {
        productName.isEmpty
    }
    
    @EnvironmentObject var monitor: NetworkMonitor
    
    var body: some View {
        ZStack{
            ScrollView{
                // 你的其他视图内容
                VStack{
                    NavigationStack {
                        Text("")
                            .frame(maxWidth:.infinity)
                            .background(Color("startColor"))
                            .opacity(1)//设置背景色
                            .navigationBarTitle("二手奢侈品交易助手", displayMode: .inline)
                            .toolbar {
                                // 修改标题字体大小
                                ToolbarItem(placement: .principal) {
                                    Text("二手奢侈品交易助手")
                                        .font(
                                            .system(size: 20, weight: .bold)
                                        ).background(Color("startColor"))
                                        .clipShape(
                                            Capsule()
                                        ) // 使用 Capsule 形状来实现圆角效果
                                }
                                ToolbarItem(placement: .navigationBarTrailing) {
                                    // 使用 toolbarTitleMenu 创建下拉菜单
                                    Menu {
                                        Button("检查更新") {
                                            networkStatus = false
                                            if monitor.isConnected {
                                                // 在这里进行更新检查
                                                self.isLoading = true
                                                 checkForAppUpdate()
                                            }else{
                                                networkStatus = true
                                            }
                                        }
                                        Button("分享") {
                                            ShareView.shareContent(content: "二手奢侈品交易助手APP",url:"http://www.pengtushuzhi.com/ptbuy/ios.html")
                                        }
                                        Button("意见反馈") {
                                            feedback = true
                                        }
                                        Button("关于") {
                                            about = true
                                        }
                                    } label: {
                                        // 设置菜单的图标
                                        Image(systemName: "gearshape.fill").imageScale(.large)
                                    }
                                }
                            }.fullScreenCover(isPresented: $about){
                                AboutView(about: $about)
                            }.fullScreenCover(isPresented: $feedback){
                                FeedBackView(feedback: $feedback)
                            }
                    }.alert("网络异常，请检查网络环境",isPresented:$networkStatus){
                        Button("关闭", role: .cancel) {
                            networkStatus = false
                        }
                    }.frame(height: 50)
                    
                    VStack{
                        HStack{
                            Text("名称：")
                            TextField("请输入名称", text: $productName)
                                .multilineTextAlignment(.center)
                                .minimumScaleFactor(0.3)
                                .onTapGesture {
                                    // 点击事件的代码
                                    isProductNameFocused = true
                                }.onChange(of: productName) { newValue in
                                    if isChose{
                                        isChose = false
                                    }else{
                                        // 每当输入变化时，过滤数据
                                        filterData(query: newValue)
                                    }
                                    
                                    
                                }
                                .overlay(
                                    Rectangle()
                                        .frame(height: 1)
                                        .foregroundColor(Color.black)
                                        .padding([.top])
                                ).focused($isProductNameFocused)
                                .cornerRadius(8)
                            
                            Text("").padding(5).frame(width: 30)
                        }
                        
                        if !filteredData.isEmpty {
                            List(filteredData, id: \.self) { item in
                                Text(item).minimumScaleFactor(0.3)
                                    .onTapGesture {
                                        // 点击某一项，更新输入框的内容
                                        productName = item
                                        filteredData = [] // 选择后隐藏列表
                                        isChose = true
                                    }
                            }
                            .frame(height: 150)
                            .cornerRadius(10)
                            .shadow(radius: 5)
                        }
                        
                    }
                    
                    HStack{
                        Text("价格：")
                        TextField("请输入价格", text: $productPrice)
                            .onTapGesture {
                                // 点击事件的代码
                                isProductPriceFocused = true
                            }
                            .keyboardType(.numberPad)
                            .overlay(
                                Rectangle()
                                    .frame(height: 1)
                                    .foregroundColor(Color.black)
                                    .padding([.top])
                            ).focused($isProductPriceFocused)
                            .cornerRadius(8)
                            .multilineTextAlignment(.center)
                        Text("元").padding(5).font(.system(size: 20))
                    }
                    HStack{
                        Button(action: {
                            // 按钮点击时的动作
                            isProductNameFocused = false
                            isProductPriceFocused = false
                            isPhotoOrView = false
                            
                            withAnimation {
                                isPhotoVideoAlertShowing.toggle()
                            }
                            
                        }) {
                            Text("拍照/录像")
                            
                        }
                        .buttonStyle(
                            MyButtonStyle(width:100,size:15,height: 40)
                        ) // 移除焦点轮廓
                        Spacer()
                        Button(
                            action: {
                                // 按钮点击时的动作
                                isProductNameFocused = false
                                isProductPriceFocused = false//关闭软键盘
                                
                                if !isProductNameTextFieldEmpty{
                                    isSaveAlertShowing = false
                                    
                                    addProduct()
                                    productPrice = ""
                                    productName=""
                                    medias.removeAll()
                                } else{
                                    isSaveAlertShowing = true
                                }
                            }) {
                                Text("保存")
                                
                            }.alert(isPresented: $isSaveAlertShowing){
                                Alert(
                                    title: Text("提示"),
                                    message: Text("请正确的填写信息"),
                                    dismissButton: .default(Text("确定"))
                                )
                                
                            }
                            .buttonStyle(
                                MyButtonStyle(width:100,size:15,height: 40)
                            )// 移除焦点轮廓
                    }.padding([.leading,.trailing],10)
                    
                    HStack{
                        Text("  总件数：\(productTotalNum)件")
                            .foregroundColor(.red)
                            .bold()
                        Spacer()
                        Text("总价：\(productTotalPrice)元  ")
                            .foregroundColor(.red)
                            .bold()
                    }.padding(5)
                    VStack{
                        ScrollView {
                            VStack() {
                                ForEach(product) { item in
                                    VStack{
                                        HStack(){
                                            if let mult = item.mult,!mult.isEmpty{
                                                let strAndJson:[String] = Utils.convertJsonStringToArray(
                                                    jsonString: mult
                                                )
                                                if strAndJson.count>0{
                                                    
                                                    if(
                                                        strAndJson[0]
                                                            .contains(".mov") || strAndJson[0]
                                                            .contains(".MOV")
                                                    ){
                                                        let filename = Utils.getDocumentsDirectory().appendingPathComponent(
                                                            strAndJson[0]
                                                        )
                                                        let player = AVPlayer(
                                                            url: URL(
                                                                fileURLWithPath: filename.path
                                                            )
                                                        );
                                                        VideoPlayer(player: player)
                                                            .frame(
                                                                width:70,
                                                                height: 100,
                                                                alignment: .center
                                                            ).padding(8)
                                                            .onTapGesture {
                                                                // 点击时，进入全屏模式
                                                                isFullScreen
                                                                    .toggle()
                                                            }.onAppear {
                                                                // 在视图显示时播放视频
                                                                player.pause()
                                                            }
                                                            .fullScreenCover(
                                                                isPresented: $isFullScreen
                                                            ) {
                                                                // 全屏播放视频
                                                                VideoPlayer(
                                                                    player: player
                                                                )
                                                                .edgesIgnoringSafeArea(
                                                                    .all
                                                                ) // 使视频全屏
                                                                .onTapGesture() {
                                                                    // 点击时，进入全屏模式
                                                                    isFullScreen
                                                                        .toggle()
                                                                }.onAppear {
                                                                    // 在视图显示时播放视频
                                                                    player.play()
                                                                }
                                                            }
                                                    }else{
                                                        
                                                        let filename = Utils.getDocumentsDirectory().appendingPathComponent(
                                                            strAndJson[0]
                                                        )
                                                        
                                                        if let uiImage = UIImage(
                                                            contentsOfFile: filename.path
                                                        ) {
                                                            Image(uiImage:uiImage)
                                                                .resizable()  // 使图片可以调整大小
                                                                .scaledToFit() // 保持图片比例，适应容器的宽高
                                                                .frame(
                                                                    width:70,
                                                                    height: 100,
                                                                    alignment: .center
                                                                ).padding(8)
                                                        }else{
                                                            Image("no_image")
                                                                .resizable()  // 使图片可以调整大小
                                                                .scaledToFit() // 保持图片比例，适应容器的宽高
                                                                .frame(
                                                                    width:70,
                                                                    height: 100,
                                                                    alignment: .center
                                                                ).padding(8)
                                                        }
                                                    }
                                                }
                                                
                                                
                                                
                                                
                                                
                                                
                                            }else{
                                                Image("no_image")
                                                    .resizable()  // 使图片可以调整大小
                                                    .scaledToFit() // 保持图片比例，适应容器的宽高
                                                    .frame(
                                                        width:70,
                                                        height: 100,
                                                        alignment: .center
                                                    ).padding(8)
                                            }
                                            
                                            
                                            VStack{
                                                VStack{
                                                    HStack{
                                                        Text("编号：")
                                                            .frame(height:12)
                                                            .font(.system(size: 12))
                                                            .multilineTextAlignment(
                                                                .leading
                                                            ).padding([.top,.leading],5)
                                                        Spacer()
                                                        Text(String(item.myorder))
                                                            .frame(height:12)
                                                            .font(.system(size: 12))
                                                            .multilineTextAlignment(
                                                                .trailing
                                                            ).padding([.top,.trailing],5)
                                                    }
                                                    Divider().background(Color.gray.opacity(0.5)).frame(height:1)
                                                }
                                                
                                               
                                                
                                                HStack{
                                                    Text("名称：")
                                                        .frame(height:12)
                                                        .font(.system(size: 12))
                                                        .multilineTextAlignment(
                                                            .leading
                                                        ).padding([.top,.leading,.bottom],5)
                                                    Spacer()
                                                    Text("")
                                                }
                                                
                                                VStack{
                                                    Divider()
                                                    Text(item.product_name ?? "")
                                                        .minimumScaleFactor(0.3)
                                                        .frame(height:30)
                                                        .font(.system(size: 12))
                                                        .edgesIgnoringSafeArea(
                                                            .all
                                                        ) // 忽略安全区域，使视图覆盖整个屏幕
                                                    
                                                    
                                                }
                                                if let ppp = item.primitive_product_price,!ppp.isEmpty{
                                            
                                                VStack{
                                                    Divider().background(Color.gray.opacity(0.5)).frame(height:1)
                                                        HStack{
                                                            Text("原始价格：")
                                                                .frame(height:12)
                                                                .font(.system(size: 12))
                                                                .multilineTextAlignment(
                                                                    .leading
                                                                ).padding([.leading],5)
                                                            Spacer()
                                                            Text("\(item.primitive_product_price ?? "")元")
                                                                .frame(height:12)
                                                                .font(.system(size: 12))
                                                                .multilineTextAlignment(
                                                                    .trailing
                                                                ).padding([.trailing],5)
                                                        }
                                                }
                                                }
                                                
                                                
                                                VStack{
                                                    Divider().background(Color.gray.opacity(0.5)).frame(height:1)
                                                    
                                                    HStack{
                                                        Text("价格：")
                                                            .frame(height:12)
                                                            .font(.system(size: 12))
                                                            .multilineTextAlignment(
                                                                .leading
                                                            ).padding([.bottom,.leading],5)
                                                        Spacer()
                                                        Text("\(item.product_price)元")
                                                            .frame(height:12)
                                                            .font(.system(size: 12))
                                                            .multilineTextAlignment(
                                                                .trailing
                                                            ).padding([.bottom,.trailing],5)
                                
                                                    }
                                                }
                                                
                                            }
                                            .frame(
                                                maxWidth: .infinity,
                                                alignment: .leading
                                            )
                                            .overlay(
                                                RoundedRectangle(cornerRadius: 0)
                                                    .stroke(
                                                        Color.black,
                                                        lineWidth: 0.5
                                                    ) // 设置边框
                                            ).edgesIgnoringSafeArea(
                                                .all
                                            ) // 忽略安全区域，使视图覆盖整个屏幕
                                            .cornerRadius(0)
                                            
                                            
                                        }.frame(
                                            maxWidth: .infinity,
                                            alignment: .leading
                                        )
                                        .overlay(
                                            RoundedRectangle(cornerRadius: 1)
                                                .stroke(
                                                    Color.black,
                                                    lineWidth: 0.5
                                                ) // 设置边框
                                        ).edgesIgnoringSafeArea(
                                            .all
                                        ) // 忽略安全区域，使视图覆盖整个屏幕
                                        .cornerRadius(1) // 设置最大宽高为无穷，确保视图覆盖全屏
                                        
                                        /*
                                         就是这个按钮撑大了父容器框
                                         */
                                        HStack{
                                            Button(action:{
                                                isDeleteProductAlert = true
                                            }){
                                                Text("删除")
                                            }.buttonStyle(
                                                MyButtonStyle(
                                                    width:80,
                                                    size:15,
                                                    height: .infinity
                                                )
                                            ).alert(
                                                "是否确认删除？",
                                                isPresented:$isDeleteProductAlert
                                            ){
                                                Button("关闭", role: .cancel) {
                                                    isDeleteProductAlert = false
                                                }
                                                Button("删除", role: .destructive) {
                                                    removeProduct(item:item)
                                                    isDeleteProductAlert = false
                                                }
                                            }
                                            Spacer()
                                            Button(
                                                action:{
                                                    productItem = item
                                                    if medias.count>0{
                                                        medias.forEach { item in
                                                            viewMediasTemp
                                                                .append(item)
                                                        }
                                                    }
                                                    medias.removeAll()
                                                    photoTemp = photo
                                                    videoTemp = video
                                                    photo = 0
                                                    video = 0
                                                    
                                                    isPhotoOrView = true
                                                    
                                                    if let mult = item.mult,
                                                       !mult.isEmpty{
                                                        
                                                        let strAndJson:[String] = Utils.convertJsonStringToArray(
                                                            jsonString: mult
                                                        )
                                                        if strAndJson.count>0{
                                                            
                                                            for str in strAndJson{
                                                                medias.append(str)
                                                                if(
                                                                    str
                                                                        .contains(
                                                                            ".mov"
                                                                        ) || str
                                                                        .contains(
                                                                            ".MOV"
                                                                        )
                                                                ){
                                                                    video += 1
                                                                }else{
                                                                    photo += 1
                                                                }
                                                            }
                                                            
                                                        }
                                                        
                                                    }
                                                    
                                                    
                                                    withAnimation {
                                                        isPhotoVideoAlertShowing
                                                            .toggle()
                                                    }
                                                    
                                                }){
                                                    Text("照片")
                                                }.buttonStyle(
                                                    MyButtonStyle(
                                                        width:80,
                                                        size:15,
                                                        height: .infinity
                                                    )
                                                )
                                            Button(
                                                action:{
                                                    productNameEdit = item.product_name ?? ""
                                                    productPriceEdit = String(
                                                        item.product_price
                                                    )
                                                    productItem = item
                                                    
                                                    withAnimation {
                                                        showingModifyProductSheet
                                                            .toggle()
                                                        
                                                    }
                                                    
                                                }){
                                                    Text("修改")
                                                }.buttonStyle(
                                                    MyButtonStyle(
                                                        width:80,
                                                        size:15,
                                                        height: .infinity
                                                    )
                                                )
                                        }.padding(8)
                                        
                                        
                                        
                                        
                                    }.frame(maxWidth:.infinity)
                                        .background(Color("endColor"))
                                        .overlay(
                                            RoundedRectangle(cornerRadius: 10)
                                                .stroke(
                                                    Color.black,
                                                    lineWidth: 0.5
                                                ) // 设置边框
                                        ).edgesIgnoringSafeArea(
                                            .all
                                        ) // 忽略安全区域，使视图覆盖整个屏幕
                                        .cornerRadius(10) // 设置最大宽高为无穷，确保视图覆盖全屏
                                        .padding([.leading,.trailing])
                                }
                            }.padding([.top,.bottom])
                        }.frame(height:UIScreen.main.bounds.height-400).simultaneousGesture(DragGesture()) // 允许内外层同时滚动
                     
                        Button(action: {
                            // 按钮点击时的动作
                            isProductNameFocused = false
                            isProductPriceFocused = false//关闭软键盘
                            isCleatAlert = true
                        }) {
                            Text("清空列表")
                        }.padding([.bottom],5)
                            .buttonStyle(
                                MyButtonStyle(width:150,size:15,height: .infinity)
                            ) // 移除焦点轮廓
                            .alert("是否确认清空列表？",isPresented:$isCleatAlert){
                                Button("关闭", role: .cancel) {
                                    isCleatAlert = false
                                }
                                Button("确定", role: .destructive) {
                                    deleteAllProduct()
                                    isCleatAlert = false
                                }
                            }
                        
                    }.frame(maxWidth:.infinity)
                        .cornerRadius(8)
                        .overlay(
                            RoundedRectangle(cornerRadius: 10)
                                .stroke(Color.black, lineWidth: 0.5) // 设置边框
                        ).padding([.leading,.trailing])
                    
                    
                    
                    HStack{
                            Button(action: {
                                // 按钮点击时的动作
                                isProductNameFocused = false
                                isProductPriceFocused = false//关闭软键盘
                                if product.count>0{
                                    withAnimation {
                                        showingSaveProductSheet.toggle()
                                    }
                                }else{
                                    isTranConfAlert  = true
                                }
                                
                                
                            }) {
                                Text("交易确认")
                                
                            }.alert("还未添加商品",isPresented:$isTranConfAlert){
                                Button("关闭", role: .cancel) {
                                    isTranConfAlert = false
                                }
                            }
                            .buttonStyle(
                                MyButtonStyle(width:100,size:15,height: 40)
                            ) // 移除焦点轮廓
                          
                        
                        Button(action: {
                            // 按钮点击时的动作
                            isProductNameFocused = false
                            isProductPriceFocused = false//关闭软键盘
                            tranRecord = true
                        }) {
                            Text("交易记录")
                            
                        }
                        .padding([.leading],10)
                        .buttonStyle(
                            MyButtonStyle(width:100,size:15,height: 40)
                        ) // 移除焦点轮廓
                        
                        
                        Button(action: {
                            // 按钮点击时的动作
                            isProductNameFocused = false
                            isProductPriceFocused = false//关闭软键盘
                            statisAnalysis = true
                            
                        }) {
                            Text("统计分析")
                            
                        } .padding([.leading],10)
                            .buttonStyle(
                               MyButtonStyle(width:100,size:15,height: 40)
                            )// 移除焦点轮廓
                        
                        //2025年01月09日 导入已有数据目前第三方库CoreXLSX导不进来，不知道是不是在虚拟机开发的原因，暂时关闭导入已有数据
//                        Button(action: {
//                            // 按钮点击时的动作
//                            isProductNameFocused = false
//                            isProductPriceFocused = false//关闭软键盘
//                            importExistData = true
//                        }) {
//                            Text("导入已有数据")
//                            
//                        }.padding([.leading],5)
//                            .buttonStyle(
//                                MyButtonStyle(width:70,size:15,height: 60)
//                            ) // 移除焦点轮廓
                    }
                }.alert("导出签字确认单成功", isPresented:$exportSuccrssAlert){
                    
                    Button("关闭",role:.cancel){
                        exportSuccrssAlert = false
                    }
                    Button("查看签字确认单",role:.cancel){
                        exportSuccrssAlert = false
                        navigateToDetail = true // 启动导航
                     
                    }
                }.alert("微信未安装",isPresented:$wxShowAlert){
                    
                    Button("关闭",role:.cancel){
                        wxShowAlert = false
                    }
                }.alert("导出签字确认单失败",isPresented:$exportFailAlert){
                   
                    Button("关闭",role:.cancel){
                        exportFailAlert = false
                    }
                }.alert(isPresented: $showUpdateAlert) {
                    Alert(
                        title: Text("发现新版本"),
                        message: Text("有新版本可用，是否更新？"),
                        primaryButton: .default(Text("更新")) {
                            // 点击更新按钮后跳转到 App Store
                            openAppStoreForUpdate()
                        },
                        secondaryButton: .cancel()
                    )
                }.padding(20)
                .fullScreenCover(isPresented: $navigateToDetail){
                    PdfViewer(fileName: $fileName,isPresented: $navigateToDetail)
                }.fullScreenCover(isPresented: $tranRecord){
                    //交易记录
                    TranRecordView(tranRecord: $tranRecord)
                }.fullScreenCover(isPresented: $statisAnalysis){
                    //统计分析
                    StatisAnalysisView(statisAnalysis: $statisAnalysis)
                }.fullScreenCover(isPresented: $importExistData){
                    //导入已有数据
                    ImportExistDataView(importExistData: $importExistData)
                }.navigationBarTitle("首页", displayMode: .inline) // 设置主页面的导航栏标题
            }
        }.background( LinearGradient(
            gradient: Gradient(
                colors: [Color("startColor").opacity(10),// 上半部分颜色，增加不透明度
                         Color("endColor").opacity(0.1)]// 上半部分颜色，增加不透明度
            ),
            startPoint: .top,
            endPoint: .bottom
        )
            .edgesIgnoringSafeArea(.all) // 忽略安全区域，使视图覆盖整个屏幕
            .frame(
                maxWidth: .infinity,
                maxHeight: .infinity
            ) // 设置最大宽高为无穷，确保视图覆盖全屏
        ).onTapGesture {
            isProductNameFocused = false
            isProductPriceFocused = false  // 点击空白区域时，移除焦点，关闭键盘
        }// 在这里使用 .overlay 添加弹窗
        .overlay(
            // 判断是否显示弹窗
            isPhotoVideoAlertShowing ? photoVideoOverlayView : nil
        ).overlay(
            showingModifyProductSheet ? modifyProductOverlayView : nil
        ).overlay(
            showingSaveProductSheet ? saveProductOverlayView : nil
        ).overlay(
            isWinShowingAlert ?  DownloadAlertView(isWinShowingAlert: $isWinShowingAlert,showAlert:$showAlert) : nil
        ).overlay(
            Group {
                if isProgressLoading {
                    VStack {
                        ProgressView("正在导出,请稍等...", value: progress, total: 100)
                            .progressViewStyle(CircularProgressViewStyle())
                            .padding()
                            .background(Color.white)
                            .cornerRadius(10)
                            .shadow(radius: 10)
                            .frame(width: 200, height: 200)
                        
                    }
                }
                if isLoading {
                    VStack {
                        ProgressView("正在检查更新,请稍等...", value: progress, total: 100)
                            .progressViewStyle(CircularProgressViewStyle())
                            .padding()
                            .background(Color.white)
                            .cornerRadius(10)
                            .shadow(radius: 10)
                            .frame(maxWidth: .infinity,minHeight:200)
                        
                    }
                }
            
            }
        ).onAppear(){
            //视图显示计算总价格和总条数
            mathProduct()
            //增加数据进数组
            addProductArray()
            isLoading = false
            Task{
                // 延时2秒测试
               try? await Task.sleep(nanoseconds: 1 * 1_000_000_000)
                print("网络状态\(monitor.isConnected)")
                if  monitor.isConnected{
                    // 页面加载时进行更新检查
                    checkForAppUpdate()
                }
               
            }
            

        }

    
    }

    
    /*
     ----------------- 拍照/录像弹框开始 -----------------
     */
    
    @State private var photo:Int8 = 0//记录已有照片数
    @State private var video:Int8 = 0//记录已有视频数
    
    @State private var photoTemp:Int8 = 0//记录临时已有照片数
    @State private var videoTemp:Int8 = 0//记录临时已有视频数
    
    @State private var permissionStatus: AVAuthorizationStatus = .notDetermined
    @State private var permissAlert = false  // 控制是否显示Alert
    
    //调用相机拍照
    @State private var isImagePickerPresented = false
    //调用相机录像
    @State private var isCameraPresented = false
    
    @State private var isImagePresented = false//点击图片全屏显示
    @State private var isFullScreen = false//点击视频全屏显示
    
    @State private var medias:[String] = [] // 图片数组，替换成你的图片名称
    
    @State private var viewMediasTemp:[String] = [] // 临时在查看的时候拍照录像里面有数据临时存放
    
    @State private var selectedImageIndex = 0 // 当前选中的图片索引
    
    @State private var isDeleteAlert = false // 当前选中的图片索引
    @State private var isDeleteVideoAlert = false // 当前选中的视频索引
    
    @State private var type:Int8 = 0//类型；0:拍照;1:选择相册
   
    var photoVideoOverlayView: some View {
        
        VStack {
            Spacer()
            // 弹窗内容
            VStack {
                HStack{
                    Button(action:{
                        permissionStatus = AVCaptureDevice
                            .authorizationStatus(for: .video)
                        type=0
                        if permissionStatus == .authorized {
                            isImagePickerPresented = true
                        }else if permissionStatus == .denied {
                            permissAlert = true
                        } else {
                            requestCameraPermission()
                        }
                                            
                    }){
                        Text("拍照").frame(width:70,height:20)
                    }.alert(isPresented: $permissAlert){
                        Alert(
                            title: Text("提示"),
                            message: Text(
                                "相机权限已被拒绝，请前往设置中开启权限"
                            ),
                            primaryButton: .destructive(Text("前往设置")) {
                                permissAlert = false
                                if let settingsURL = URL(
                                    string: UIApplication.openSettingsURLString
                                ) {
                                    UIApplication.shared.open(settingsURL)
                                }
                            },
                            secondaryButton: .cancel(Text("关闭")) {
                                permissAlert = false
                            })
                    }.sheet(isPresented: $isImagePickerPresented) {
                        ImagePicker(isImagePickerPresented: $isImagePickerPresented,
                                    medias:$medias,
                                    type:$type,
                                    photo:$photo)
                    }.padding()
                        .foregroundColor(.black)
                        .background(Color(red: 0.8, green: 0.8, blue: 0.8))
                        .cornerRadius(8)
                    Spacer()
                    Button(action:{
                        isCameraPresented = true
                    }){
                        Text("录像").frame(width:70,height:20)
                    }.sheet(isPresented: $isCameraPresented) {
                        VideoPicker(
                            isPresented: $isCameraPresented,
                            medias:$medias,
                            video:$video
                        )
                    }.padding()
                        .foregroundColor(.black)
                        .background(Color(red: 0.8, green: 0.8, blue: 0.8))
                        .cornerRadius(8)
                    Spacer()
                    
                    Button(action:{
                        type=1
                        isImagePickerPresented = true
                    }){
                        Text("相册").frame(width:70,height:20)
                    }.sheet(isPresented: $isImagePickerPresented) {
                        ImagePicker(isImagePickerPresented: $isImagePickerPresented,
                                    medias:$medias,
                                    type:$type,
                                    photo:$photo)
                    }.padding()
                        .foregroundColor(.black)
                        .background(Color(red: 0.8, green: 0.8, blue: 0.8))
                        .cornerRadius(8)
                                        
                }.padding()
                
                Text("已有：照片：\(photo)张；视频：\(video)个")
                    .multilineTextAlignment(.leading)
                    .padding(.horizontal, 10)
                TabView (selection: $selectedImageIndex){

                    ForEach(0..<medias.count, id: \.self) { index in
                        if(
                            medias[index]
                                .contains(".mov") ||  medias[index]
                                .contains(".MOV")
                        ){
                            VStack{
                                HStack{
                                    Text("")
                                    Spacer()
                                    Image("shanchu") // 这里不需要加文件扩展名
                                        .resizable()   // 使图片可调整大小
                                        .scaledToFit() // 保持图片比例
                                        .frame(width: 25, height: 25) // 设置图片的尺寸
                                        .padding([.top,.trailing],8)
                                        .onTapGesture(){
                                            isDeleteVideoAlert = true
                                        }.alert(
                                            "确定删除此视频吗？",
                                            isPresented:$isDeleteVideoAlert
                                        ){
                                            Button("关闭", role: .cancel) {
                                                isDeleteVideoAlert = false
                                            }
                                            Button("删除", role: .destructive) {
                                                
                                                medias
                                                    .remove(
                                                        at: selectedImageIndex
                                                    )
                                                if isPhotoOrView{
                                                    modifyProductMedia(
                                                        item:productItem,
                                                        type:2
                                                    )
                                                }else{
                                                    video -= 1
                                                }
                                                
                                                isDeleteVideoAlert = false
                                            }
                                        }
                                }
                                let filename = Utils.getDocumentsDirectory().appendingPathComponent(
                                    medias[index]
                                )
                                
                                let player = AVPlayer(
                                    url: URL(fileURLWithPath: filename.path)
                                );
                                VideoPlayer(player: player)
                                    .onTapGesture {
                                        // 点击时，进入全屏模式
                                        isFullScreen = true
                                    }.onAppear {
                                        // 在视图显示时播放视频
                                        player.pause()
                                    }.fullScreenCover(
                                        isPresented:$isFullScreen
                                    ){
                                        let filename = Utils.getDocumentsDirectory().appendingPathComponent(
                                            medias[selectedImageIndex]
                                        )
                    
                                        let player = AVPlayer(
                                            url: URL(
                                                fileURLWithPath: filename.path
                                            )
                                        );
                                        // 全屏播放视频
                                        VideoPlayer(player: player)
                                            .edgesIgnoringSafeArea(
                                                .all
                                            ) // 使视频全屏
                                            .onTapGesture() {
                                                // 点击时，进入全屏模式
                                                isFullScreen = false
                                                player.pause()
                                            }.onAppear {
                                                // 在视图显示时播放视频
                                                player.play()
                                            }
                                    }

                            }
                        }else{
                            let filename = Utils.getDocumentsDirectory().appendingPathComponent(
                                medias[index]
                            )
                            if let uiImage = UIImage(
                                contentsOfFile: filename.path
                            ) {
                                
                                VStack{
                                    HStack{
                                        Text("")
                                        Spacer()
                                        Image("shanchu") // 这里不需要加文件扩展名
                                            .resizable()   // 使图片可调整大小
                                            .scaledToFit() // 保持图片比例
                                            .frame(
                                                width: 25,
                                                height: 25
                                            ) // 设置图片的尺寸
                                            .padding([.top,.trailing],8)
                                            .onTapGesture(){
                                                isDeleteAlert = true
                                            }.alert(
                                                "确定删除此照片吗？",
                                                isPresented:$isDeleteAlert
                                            ){
                                                Button("关闭", role: .cancel) {
                                                    isDeleteAlert = false
                                                }
                                                Button(
                                                    "删除",
                                                    role: .destructive
                                                ) {
                                                    medias.remove(at: selectedImageIndex)
                                                    if isPhotoOrView{
                                                        modifyProductMedia(
                                                            item:productItem,
                                                            type:1
                                                        )
                                                    }else{
                                                        photo -= 1
                                                    }
                                                   
                                                   
                                                    isDeleteAlert = false
                                                }
                                            }
                                    }
                                   
                                    
                                    // 从文件路径加载图片
                                    Image(uiImage: uiImage)
                                        .resizable()  // 使图片可调整大小
                                        .scaledToFit()  // 保持比例缩放
                                        .frame(
                                            width: UIScreen.main.bounds.width,
                                            height: 300
                                        )
                                    // 设置显示尺寸
                                        .padding()
                                        .onTapGesture {
                                            // 点击图片时，显示大图
                                            isImagePresented = true
                                        }.fullScreenCover(
                                            isPresented: $isImagePresented
                                        ) {
                                            let filename = Utils.getDocumentsDirectory().appendingPathComponent(
                                                medias[selectedImageIndex]
                                            )
                                            if let uiImage = UIImage(
                                                contentsOfFile: filename.path
                                            ) {
                                                // 显示大图的视图
                                                Image(
                                                    uiImage: uiImage
                                                ) // 用你的图片名称替换
                                                .resizable()
                                                .scaledToFit()
                                                .edgesIgnoringSafeArea(.all)
                                                .onTapGesture {
                                                    // 点击大图时关闭
                                                    isImagePresented.toggle()
                                                }
                                            }
                                          
                                        }
                                }
                                
                                

                            } else {
                                Text("File not found")
                                    .foregroundColor(.red)
                            }
                        }
                       
                    }
                }.tabViewStyle(
                    PageTabViewStyle(indexDisplayMode: .always)
                )// 启用分页样式
                .frame(height: 350) // 设定图片视图的高度
                .background(Color(red: 0.8, green: 0.8, blue: 0.8))
                .padding()
                        
                
                HStack {
                    Button(action:{
                        if isPhotoOrView{
                            retyPicAndVideo()
                        }
                        withAnimation {
                            isPhotoVideoAlertShowing = false
                        }
                    }) {
                        Text("关闭").padding().frame(
                            maxWidth: .infinity,
                            alignment: .center
                        )
                    }
                    .overlay(
                        RoundedRectangle(
                            cornerRadius: 8
                        )
                        .stroke(
                            Color.black,
                            lineWidth: 0.5
                        ) // 设置边框
                    ).edgesIgnoringSafeArea(
                        .all
                    ) // 忽略安全区域，使视图覆盖整个屏幕
                    .cornerRadius(
                        8
                    ) // 设置最大宽高为无穷，确保视图覆盖全屏
                            
                    Button(action:{
                        // 这里是按钮的点击事件
                        if isPhotoOrView{
                            modifyProduct(item: productItem)
                        }
                            
                            
                        withAnimation {
                            isPhotoVideoAlertShowing = false
                        }
                    }) {
                        Text("确定").padding().frame(
                            maxWidth: .infinity,
                            alignment: .center
                        )
                           
                    }
                    .overlay(
                        RoundedRectangle(
                            cornerRadius: 8
                        )
                        .stroke(
                            Color.black,
                            lineWidth: 0.5
                        ) // 设置边框
                    ).edgesIgnoringSafeArea(
                        .all
                    ) // 忽略安全区域，使视图覆盖整个屏幕
                    .cornerRadius(
                        8
                    ) // 设置最大宽高为无穷，确保视图覆盖全屏
                            
                }
                
            }
            .frame(maxWidth: .infinity, minHeight: 200)
            .background(Color.white)
            .cornerRadius(12)
            .shadow(radius: 8)
            .padding(.horizontal, 30)
                        
            Spacer()
        } .background(
            // 背景遮罩
            Color.black.opacity(0.5)
                .edgesIgnoringSafeArea(.all)
            
        )
 
        
    }
    
    /*
     ----------------- 拍照/录像弹框结束 -----------------
     */
    
    
    /*
     --------------商品编辑弹框开始--------------
     */
    
    @State private var productItem :Product
    
    var modifyProductOverlayView: some View {
        VStack {
            Spacer()
            VStack{
                Text("修改")
                    .font(.headline)
                    .padding()
                Form {
                    Section(header: Text("")) {
                        HStack{
                            Text("名称：")
                            TextField(
                                "名称",
                                text: $productNameEdit
                            ).minimumScaleFactor(0.3)
                                .textFieldStyle(
                                    RoundedBorderTextFieldStyle()
                                )
                           
                        }.padding([.top,.bottom],8)
                        
                        HStack{
                            Text("价格：")
                            TextField(
                                "价格",
                                text: $productPriceEdit
                            ).keyboardType(.numberPad)
                                .textFieldStyle(
                                    RoundedBorderTextFieldStyle()
                                )
                               
                        }.padding([.top,.bottom],8)
                        
                    }
                    
                }.frame(height: 200)  // 使 Form 自适应内容高度
                HStack {
                    Button(action:{
                        showingModifyProductSheet = false
                    }) {
                        Text("取消").padding().frame(
                            maxWidth: .infinity,
                            alignment: .center
                        )
                    }
                    .overlay(
                        RoundedRectangle(
                            cornerRadius: 8
                        )
                        .stroke(
                            Color.black,
                            lineWidth: 0.5
                        ) // 设置边框
                    ).edgesIgnoringSafeArea(
                        .all
                    ) // 忽略安全区域，使视图覆盖整个屏幕
                    .cornerRadius(
                        8
                    ) // 设置最大宽高为无穷，确保视图覆盖全屏
                            
                    Button(action:{
                        // Handle form submission
                        modifyProduct(item:productItem)
                        showingModifyProductSheet = false
                    }) {
                        Text("确定").padding().frame(
                            maxWidth: .infinity,
                            alignment: .center
                        )
                           
                    }
                    .overlay(
                        RoundedRectangle(
                            cornerRadius: 8
                        )
                        .stroke(
                            Color.black,
                            lineWidth: 0.5
                        ) // 设置边框
                    ).edgesIgnoringSafeArea(
                        .all
                    ) // 忽略安全区域，使视图覆盖整个屏幕
                    .cornerRadius(
                        8
                    ) // 设置最大宽高为无穷，确保视图覆盖全屏
                            
                }
            }.frame(maxWidth: .infinity, minHeight: 200)
                .background(Color.white)
                .cornerRadius(12)
                .shadow(radius: 8)
                .padding(.horizontal, 30)
                            
            Spacer()
        }.background(
            // 背景遮罩
            Color.black.opacity(0.5)
                .edgesIgnoringSafeArea(.all)
            
        )
    }
    /*
     --------------商品编辑弹框结束--------------
     */
    
    /*
     -------------交易确认弹框开始----------------
     */
    
    @State private var clientName:String = ""//客户名称
    @State private var clientPhone:String = ""//客户电话
    @State private var clientAgentName:String = ""//收购人
    @State private var clientSignPath:String = ""//客户签名文件
    
    @State private var saveAlert = false//保存提示框
    @State private var saveFailAlert = false//保存失败提示框
    @State private var saveSuccessAlert = false//保存成功提示框
    

    @State private var exportSuccrssAlert = false//导出成功提示框
    @State private var exportFailAlert = false//导出失败提示框
    
    @State private var navigateToDetail = false // 控制导航跳转
    @State private var fileName = "" // 用于传递参数
    
    @EnvironmentObject var appDelegate: AppDelegate // 引用 AppDelegate
    var saveProductOverlayView: some View {
        VStack{
            Spacer()
            NavigationView {
                VStack{
                    Text("交易确认")
                        .font(.headline)
                        .padding()
                    
                    Form {
                        Section(header: Text("")) {
                            HStack{
                                Text("客户姓名：").font(.system(size:15))
                                TextField(
                                    "请输入客户姓名",
                                    text: $clientName
                                ).minimumScaleFactor(0.3)
                                    .textFieldStyle(
                                        RoundedBorderTextFieldStyle()
                                    ).font(.system(size:15))
                                
                            }.padding([.top,.bottom],5)
                            
                            HStack{
                                Text("客户电话：").font(.system(size:15))
                                TextField(
                                    "请输入客户电话",
                                    text: $clientPhone
                                ).keyboardType(.numberPad)
                                    .textFieldStyle(
                                        RoundedBorderTextFieldStyle()
                                    ).font(.system(size:15))
                                
                            }.padding([.top,.bottom],5)
                            
                            HStack{
                                Text("收  购  人：").font(.system(size:15))
                                TextField(
                                    "请输入收购人",
                                    text: $clientAgentName
                                ).minimumScaleFactor(0.3)
                                    .textFieldStyle(
                                        RoundedBorderTextFieldStyle()
                                    ).font(.system(size:15))
                                
                            }.padding([.top,.bottom],5)
                            
                            
                            // 跳转到签名页面
                            NavigationLink("客户签名", destination: SignatureView(clientSignPath: $clientSignPath))
                                .padding()
                                .background(Color.blue)
                                .foregroundColor(.white)
                                .cornerRadius(10)
                                .frame(maxWidth: .infinity, alignment: .center)
                        
                        if clientSignPath != ""{
                            let filename = Utils.getDocumentsDirectory().appendingPathComponent(
                                clientSignPath
                            )
                            if let uiImage = UIImage(
                                contentsOfFile: filename.path
                            ) {
                                Image(uiImage:uiImage)
                                    .resizable()  // 使图片可调整大小
                                    .scaledToFit()  // 保持比例缩放
                                    .frame(
                                        maxWidth: .infinity,
                                        maxHeight:100
                                       
                                    )
                            }
                            
                        }
                        
                        
                    }
                    
                }.frame(height: 450)  // 使 Form 自适应内容高度
                .onAppear{
                    appDelegate.unlockOrientation()
                }
                    
                    
                HStack {
                    Button(action:{
                        showingSaveProductSheet = false
                    }) {
                        Text("取消").padding().frame(
                            maxWidth: .infinity,
                            alignment: .center
                        )
                    }
                    .overlay(
                        RoundedRectangle(
                            cornerRadius: 8
                        )
                        .stroke(
                            Color.black,
                            lineWidth: 0.5
                        ) // 设置边框
                    ).edgesIgnoringSafeArea(
                        .all
                    ) // 忽略安全区域，使视图覆盖整个屏幕
                    .cornerRadius(
                        8
                    ) // 设置最大宽高为无穷，确保视图覆盖全屏
                            
                    Button(action:{
                        
                        if clientName==""{
                            saveAlert=true
                        }else{
                            let save = saveClient()//保存客户信息
                            if(save==""){
                                saveFailAlert = true
                            }else{
                                saveSuccessAlert = true
                                //保存成功清空输入框
                                productTotalPrice = 0
                                
                                productTotalNum = 0
                                
                            }
                        }
                    
                        
                    }) {
                        Text("确定").padding().frame(
                            maxWidth: .infinity,
                            alignment: .center
                        )
                           
                    }.alert("请填写客户名称", isPresented:$saveAlert){
                        Button("关闭",role:.cancel){
                            saveAlert = false
                        }
                    }.alert("客户信息保存失败", isPresented:$saveFailAlert){
                        Button("关闭",role:.cancel){
                            saveFailAlert = false
                        }
                    }.alert("客户信息保存成功,是否导出签字确认单？", isPresented:$saveSuccessAlert){
                        Button("关闭",role:.cancel){
                            saveFailAlert = false
                            showingSaveProductSheet = false
                            clientName = ""
                            clientPhone = ""
                            clientAgentName = ""
                            clientSignPath = ""
                        }
                        Button("导出",role:.destructive){
                            saveFailAlert = false
                            showingSaveProductSheet = false
                            isProgressLoading = true
                            
                            do{
                                Task{
                                    /*
                                     签名文件为空，用户信息这些都为空，在上面设置为空了
                                     */
                                    for object in productPojo {
                                        let productName : String = object.product_name ?? ""
                                        let time : String = object.time ?? ""
                                        productPojo.append(ProductPojo(product_name: productName,
                                                                       product_price: String(object.product_price),
                                                                       time: time,clientName:clientName,clientPhone:clientPhone,
                                                                       clientAgentName:clientAgentName))
                                    }
                                    
                                    // 使用函数生成PDF
                                    fileName =   try await createPDF(product:productPojo,
                                              clientSignPath:clientSignPath,
                                              myFileName:"",
                                              isSign:true)
                                    print(fileName)
                                    saveExport()//导出成功保存签字确认单
                                   /*
                                    提示导出成功，保存导出信息入库,清空临时存储数据
                                    */
                                   productPojo.removeAll()
                                    clientName = ""
                                    clientPhone = ""
                                    clientAgentName = ""
                                    clientSignPath = ""
                                }
                           }catch{
                               /*
                                提示导出失败
                                */
                               exportSuccrssAlert = false
                               exportFailAlert = true
                               clientName = ""
                               clientPhone = ""
                               clientAgentName = ""
                               clientSignPath = ""
                           }
                            isProgressLoading = false
                            exportSuccrssAlert = true
                            exportFailAlert = false
                          
                        }
                    }
                    .overlay(
                        RoundedRectangle(
                            cornerRadius: 8
                        )
                        .stroke(
                            Color.black,
                            lineWidth: 0.5
                        ) // 设置边框
                    ).edgesIgnoringSafeArea(
                        .all
                    ) // 忽略安全区域，使视图覆盖整个屏幕
                    .cornerRadius(
                        8
                    ) // 设置最大宽高为无穷，确保视图覆盖全屏
                            
                }
            }.frame(maxWidth: .infinity-200, minHeight: 200)
                .background(Color.white)
                .cornerRadius(12)
                .shadow(radius: 8)
                .padding(.horizontal, 5)
            } .navigationTitle("首页")
            
            Spacer()
        }.background(
            // 背景遮罩
            Color.black.opacity(0.5)
            
        )
    }

    /*
     -------------交易确认弹框结束----------------
     */
    
    
    func requestCameraPermission() {
        AVCaptureDevice.requestAccess(for: .video) { response in
            DispatchQueue.main.async {
                permissionStatus = AVCaptureDevice
                    .authorizationStatus(for: .video)
            }
        }
    }

    @State var order:Int16 = 0;
    
  
    
    // 增加一条数据
    private func addProduct() {
        let newProduct = Product(context: viewContext)
        newProduct.id = UUID().uuidString
            .replacingOccurrences(of: "-", with: "")// 或者其他类型，确保是唯一的标识
        newProduct.product_name = productName
        
        newProduct.product_price = Int64(productPrice) ?? 0
        newProduct.time = formattedDate()
        newProduct.inttime = Int64(formattedDateInt()) ?? 0
        if !medias.isEmpty{
            
            let jsonString =  Utils.convertArrayToJsonString(
                stringArray: medias
            )
            if(jsonString != ""){
                newProduct.mult = jsonString
            }
        }
        // 计算属性来获取product数组中myorder属性的最大值
        let orderS = product.max(by: { $0.myorder < $1.myorder })?.myorder
      
        let myorder: Int16 = (orderS ?? 0)
        order = myorder+1
      
        newProduct.myorder = order
        newProduct.status = 0
        
        
        do {
            try viewContext.save()
            
            mathProduct()
            addProductArray()
            
        } catch {
            // 处理错误
            print("Error saving context: \(error.localizedDescription)")
        }
    }
   
    // 创建日期格式化器
    func formattedDateInt() -> String {
        let formatter = DateFormatter()
        // 获取当前时间
        let currentDate = Date()
        formatter.dateFormat = "yyyyMMdd"
        return formatter.string(from: currentDate)
    }
    
    // 创建日期格式化器
    func formattedDate() -> String {
        let formatter = DateFormatter()
        // 获取当前时间
        let currentDate = Date()
        formatter.dateStyle = .long
        formatter.timeStyle = .medium
        return formatter.string(from: currentDate)
    }
    
    //删除商品信息
    private func removeProduct(item: Product) {
        viewContext.delete(item)
        do {
            try viewContext.save()
            mathProduct()
            addProductArray()
        } catch {
            print("Failed to delete item: \(error.localizedDescription)")
        }
    }
    
    //清空列表
    private func deleteAllProduct(){
        if product.count>0{
            for item in product {
                viewContext.delete(item)
            }
            
            do {
                // 执行批量删除
                try viewContext.save()
                print("Batch delete successful.")
                mathProduct()
            } catch {
                print("Failed to perform batch delete: \(error)")
            }
        }
        
    }

    //修改商品信息
    private func modifyProduct(item: Product) {
        if isPhotoOrView{
            
            if !medias.isEmpty{
                item.mult = Utils.convertArrayToJsonString(stringArray: medias)
            }else{
                item.mult = nil
            }
        }else{
            item.product_name = productNameEdit
            item.product_price = Int64(productPriceEdit) ?? 0
        }
        
       
        
        do {
            if isPhotoOrView{
                try viewContext.save()
                retyPicAndVideo()
            }else{
                try viewContext.save()
                mathProduct()
                addProductArray()
            }
        } catch {
            print("Failed to update item: \(error.localizedDescription)")
        }
    }
    
    
    //修改商品多媒体信息
    private func modifyProductMedia(item:Product,type:Int8) {
        if !medias.isEmpty{
            item.mult = Utils.convertArrayToJsonString(stringArray: medias)
        }else{
            item.mult = nil
        }
        
        
        do {
            try viewContext.save()
            if type==1{
                photo-=1
            }else{
                video-=1
            }
        } catch {
            print("Failed to update item: \(error.localizedDescription)")
        }
    }
    
    //还原照片视频框
    private func retyPicAndVideo(){
        medias.removeAll()
        if viewMediasTemp.count>0{
            viewMediasTemp.forEach { item in
                medias.append(item)
            }
            viewMediasTemp.removeAll()
            isPhotoOrView = false
        }
       
        photo = photoTemp
        video = videoTemp
        photoTemp = 0
        videoTemp = 0
    }
    
    //计算总价格和总条数
    private func mathProduct(){
        productTotalNum = Int16(product.count)
        productTotalPrice = product.map(\.product_price).reduce(0,+)
        photo = 0
        video = 0
    }
    /*
     商品名称输入匹配
     */
    private func filterData(query: String) {
        // 如果搜索文本为空，清空过滤列表
        if query.isEmpty {
            filteredData = []
        } else {
            // 根据搜索文本过滤数据源
            filteredData = productArray
                .filter { $0.lowercased().contains(query.lowercased()) }
        }
    }
    
    //增加数据进数组,先清空后增加
    private func addProductArray(){
        productArray.removeAll()
        for product in productAll {
                 if let name = product.product_name {
                     if !productArray.contains(name){
                         productArray.append(name)
                     }
                 }
             }
        
        productPojo.removeAll()

        for object in product {
            let productName : String = object.product_name ?? ""
            let time : String = object.time ?? ""
            productPojo.append(ProductPojo(product_name: productName,
                                           product_price: String(object.product_price),
                                           time: time,clientName:"",clientPhone:"",
                                           clientAgentName:"clientAgentName"))
        }
    }
    
    /*
      -------------------客户信息操作地方开始------------------------------
     */
    
    
    @State private var clientOrder:Int16 = 0
    @State private var clientId:String = ""
    
   private func saveClient()->String{
        let newclient = Client(context:viewContext)
       
       clientId =  UUID().uuidString
           .replacingOccurrences(of: "-", with: "")// 或者其他类型，确保是唯一的标识
       
        newclient.id = clientId
        if clientAgentName != ""{
            newclient.agent_name = clientAgentName
        }
        // 计算属性来获取product数组中myorder属性的最大值
        let orderS = client.max(by: { $0.myorder < $1.myorder })?.myorder
      
        let myorder: Int16 = (orderS ?? 0)
        clientOrder = myorder+1
      
        newclient.myorder = clientOrder
        
        if clientName != ""{
            newclient.name = clientName
        }
        
        if clientPhone != ""{
            newclient.phone = clientPhone
        } 
        if clientSignPath != ""{
            newclient.signatureFilePath = clientSignPath
        }
        
        newclient.time = formattedDate()
        newclient.inttime = Int64(formattedDateInt()) ?? 0
        
        newclient.total_price =  Int64(productTotalPrice)
        
        newclient.total_product  = productTotalNum
        
        do {
           try viewContext.save()
           //保存成功后修改商品状态为1
           modifyProductStatus()
           return "success"
       } catch {
           // 处理错误
           print("Error saving context: \(error.localizedDescription)")
           return ""
       }
    }
    //保存签字确认单
    private func saveExport(){
        let export = Export(context:viewContext)
        export.id = UUID().uuidString
            .replacingOccurrences(of: "-", with: "")// 或者其他类型，确保是唯一的标识
        export.clientid = clientId
        print(fileName)
        export.exportFilePath = fileName
        export.exportDate = formattedDate()
        do{
            try viewContext.save()
            clientId = ""
        }catch{
            print("Error saving context: \(error.localizedDescription)")
        }
    }
    
   private func modifyProductStatus(){
       do{
           for item in product{
               item.status = 1
               item.pid = clientId
           }
           try viewContext.save()
           // 成功处理
            print("Success to update items")
       }catch{
           // 错误处理
           print("Failed to update items: \(error)")
       }
    }
    
    /*
      -------------------客户信息操作地方结束----------------------------
     */
    
    
    /*
     --------------------APP更新检测开始------------------------
     */
        // 检查更新按钮的操作
        func checkForAppUpdate() {
            let currentVersion = Utils.appVersion()
            let appId = "YOUR_APP_ID"
            let url = URL(string: "https://itunes.apple.com/lookup?id=\(appId)")!
            
            let task = URLSession.shared.dataTask(with: url) { data, response, error in
                if let error = error {
                    print("Error checking for update: \(error)")
                    self.isLoading = false
                    return
                }
                
                if let data = data {
                    do {
                        let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
                        if let results = json?["results"] as? [[String: Any]], let appInfo = results.first {
                            if let latestVersion = appInfo["version"] as? String {
                                // 比较版本
                                if currentVersion != latestVersion {
                                    DispatchQueue.main.async {
                                        self.showUpdateAlert = true
                                    }
                                }
                            }
                        }
                    } catch {
                        print("Failed to parse JSON: \(error)")
                    }
                    self.isLoading = false
                }
            }
            
            task.resume()
        }
        
        // 打开 App Store
        func openAppStoreForUpdate() {
            if let appStoreURL = URL(string: "itms-apps://itunes.apple.com/app/idYOUR_APP_ID") {
                if UIApplication.shared.canOpenURL(appStoreURL) {
                    UIApplication.shared.open(appStoreURL, options: [:], completionHandler: nil)
                }
            }
        }
    
    /*
     --------------------APP更新检测结束------------------------
     */
}
                                                                         
#Preview {
    MainPage()
}
